package self.cloud.domain.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import self.cloud.domain.aliyun.AliyunDomainService;
import self.cloud.domain.config.DomainConfig;
import self.cloud.domain.core.entity.DomainRecord;
import self.cloud.domain.network.NetworkBusiness;
import self.cloud.domain.network.entity.AddressType;

import java.net.SocketException;

@Component
public class ScheduledTasks {
    private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);

    @Autowired
    DomainConfig domainConfig;

    @Autowired
    NetworkBusiness networkBusiness;

    @Autowired
    AliyunDomainService aliyunDomainService;

    private static DomainRecord domainRecord;

    @Scheduled(fixedDelay = 10 * 1000)
    public void checkIpv6() {
        logger.info("method checkIpv6");
        if(domainRecord == null) {
            domainRecord = new DomainRecord(this.domainConfig.getRecordRr(), this.domainConfig.getRecordType(), null);
        }

        // check network
        if(this.domainConfig.getNetwork() == null || this.domainConfig.getNetwork().equals("")) {
            logger.error("Cannot find network");
            try {
                logger.warn(this.networkBusiness.findAllToString());
            } catch (SocketException e) {
                logger.error(e.toString(), e);
            }
            return;
        }

        String hostAddress = null;

        try {
            hostAddress = this.networkBusiness.getHostAddress(this.domainConfig.getNetwork(), AddressType.IPV6);
        } catch (SocketException e) {
            logger.error(e.toString(), e);
            return;
        }

        if (hostAddress == null) {
            logger.error("Cannot find hostAddress");
            return;
        }

        logger.info("[{}]:{}", this.domainConfig.getNetwork(), hostAddress);
        domainRecord.setValue(hostAddress);

        try {
            this.aliyunDomainService.set(this.domainConfig.getName(), domainRecord);
        }

        catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }
}